package com.zhaoqi.hr.config;

import com.zhaoqi.hr.entity.User;
import com.zhaoqi.hr.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 数据初始化配置
 */
@Component
public class DataInitializer implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        initializeAdminUser();
    }

    /**
     * 初始化管理员用户
     */
    private void initializeAdminUser() {
        if (!userRepository.existsByUsername("admin")) {
            User admin = new User();
            admin.setUsername("admin");
            admin.setPhone("13800000000");
            admin.setPassword(passwordEncoder.encode("admin123"));
            admin.setRealName("系统管理员");
            admin.setRole(User.UserRole.EMPLOYER);
            admin.setStatus(User.UserStatus.APPROVED);

            userRepository.save(admin);
            log.info("管理员用户初始化完成: username=admin, password=admin123");
        } else {
            log.info("管理员用户已存在，跳过初始化");
        }
    }
}
